//
//  ReaderViewController.m
//  ebook
//
//  Crea  ted by 吴超飞 on 16/1/15.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "ReaderViewController.h"
#import "ReaderGlobalModel.h"
#import "ReaderToolBar.h"
#import "ReaderTopBar.h"
#import "DatasourceViewController.h"
#import "MBProgressHUD.h"
#import "FmdbAccess.h"
#import "SettimeModel.h"
#import "EbookNetRequest.h"
#import "MTPageViewController.h"
#import "FileManager.h"
#import "DownloadManager.h"
#import "MISAlertController.h"
#import "SettingViewController.h"
#import "FontSetViewController.h"
#import "MTNavigationController.h"
#import "SelectSourceViewController.h"
#import "PageScrollVerticalView.h"
#import "BookcaseOprationController.h"
#import "WebViewController.h"
#import "AutoScrollReadingToolBar.h"
#import "PhoneticReadingManager.h"
#import "PhoneticReadingToolBar.h"
#import "PhoneticReadingPlayBtn.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "InterstitialAdView.h"
#import "MTRotatingScreen.h"

#define kLeftPagedown [[NSUserDefaults standardUserDefaults] boolForKey:kSetClipLeftPageDown] //点击左侧下翻页

#define AREADY_TO_LAST  @"已经到了最后一章了"
#define AREADY_TO_FRONT @"前面没有了"
#define MINTIMERINTERVAL 1
#define VOICEDIVID   @"...... 。。。。。。。。。。。。" //-----------  语音段落分割符号

typedef void (^Completion)(void);

@interface ReaderViewController ()<UIGestureRecognizerDelegate,ReaderToolBarDelegate,ReaderTopBarDelegate,DatasourceViewControllerDelegate,UIScrollViewDelegate,UIViewControllerTransitioningDelegate,PageScrollVerticalViewDelegate,AutoScrollReadingToolBarDelegate,PhoneticReadingManagerDelegate,PhoneticReadingToolBarDelegate,PhoneticReadingPlayBtnDelegate>{
    
    BOOL isShowBookmarkMenuview;//是否显示目录、书签视图
    Bookmark *lastReadnode;//上次阅读位置、定时器定时处理存储
    double lastRecordNodeTime;
    __block BOOL isExcutingUpdate;
    DataViewController *willVc;//滑动翻页时下一个将要显示的视图
}

@property (retain, nonatomic) UIPageViewController *pageController;
@property (retain, nonatomic) DatasourceViewController *dsController;

@property (retain, nonatomic) ReaderGlobalModel *globalModel;
@property (retain, nonatomic) ReaderToolBar *toolbar;
@property (retain, nonatomic) ReaderTopBar *topbar;
@property (assign, nonatomic) BOOL isShowMenu;
@property (retain, nonatomic) MBProgressHUD *HUD;
@property (strong, nonatomic) dispatch_source_t nightModeTimer;

//上下滚动翻页
@property (strong, nonatomic) PageScrollVerticalView *pageScrollView;
//屏幕旋转
@property (nonatomic, assign) BOOL isScreenRotating;

//自动阅读Bar
@property (nonatomic, strong) AutoScrollReadingToolBar *autoScrollReadingToolBar;
//自动阅读 计时器
@property (nonatomic, strong) NSTimer *autoScrollReadingTimer;

//浮动的播放按钮
@property (nonatomic, strong) PhoneticReadingPlayBtn *phoneticReadingPlayBtn;
//语音阅读toolBar
@property (nonatomic, strong) PhoneticReadingToolBar *phoneticReadingToolBar;
//语音阅读上面覆盖的透明的view
@property (nonatomic, strong) UIView *phoneticCoverView;

@property (nonatomic, retain) InterstitialAdView *interstitialAdView;//插屏广告

@end

@implementation ReaderViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //判断当前是否处在夜间模式有效时段中
    if([SettimeModel isInNightTimeInteval])
        [ReaderGlobalModel shareModel].readerConfig.IsNight = YES;
    
    //取消导航条对视图的影响
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self addTapGesture];
    if (self.globalModel.readerConfig.PageTurnStyle == PageTurnStyle_Updown) {
        [self initPageScrollView];
    } else {
        [self initPageViewController];
        [self pageControllerSetIndex:self.dsController.index animated:NO direct:UIPageViewControllerNavigationDirectionForward isDoubleSide:NO completion:nil];
    }
    
    [self setupReaderBar];
    [self.phoneticReadingPlayBtn hide];
    
    [self addNotificationObserver];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    BOOL isLightScreen = [[NSUserDefaults standardUserDefaults] boolForKey:kSetLightOfScreen];
    [[UIApplication sharedApplication] setIdleTimerDisabled:isLightScreen];
}

-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    // 禁用返回手势
    [self enableInteractivePopGestureRecognizer:NO];
    
    [self nightModeTimerTask];
    
    [self enterForeground:nil];
}

-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    [self bookmarkSaveImmediately:YES];
    [self cancelTimer];
}

-(void)addNotificationObserver{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadTaskFinishOne:) name:kFinishOneDownloadTaskNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadTaskCancel:) name:kDownloadTaskCancelNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateFont) name:KApplyFontNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshConten:) name:kRefreshAdnReloadChapterNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    
    //语音阅读中断处理
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
}

-(void)enterForeground:(NSNotification*)noti{
   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([ReaderGlobalModel shareModel].readerConfig.orientationIsLandscape && [MTRotatingScreen isOrientationPortrait]) {
            [self readerToolBar:self.toolbar orientationIsLandscape:YES];
            [ToastView showMsg:@"切换回横屏模式" inView:self.view isCenter:YES];
        }
    });
}

-(void)appEnterBackground:(NSNotification*)noti{
    [self bookmarkSaveImmediately:YES];
}

#pragma mark -
- (DatasourceViewController *)dsController {
    
    if (!_dsController) {
        _dsController = [[DatasourceViewController alloc] init];
        _dsController.delegate = self;
    }
    return _dsController;
}

- (ReaderGlobalModel *)globalModel
{
    if (!_globalModel) {
        _globalModel = [ReaderGlobalModel shareModel];
    }
    return _globalModel;
}

-(MBProgressHUD *)HUD{
    
    if (!_HUD) {
        _HUD = [[MBProgressHUD alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
        _HUD.labelText = kInfoReadingLoad;
    }
    _HUD.minShowTime = 1.0;
    return _HUD;
}

-(void)showHud:(BOOL)islocal{
    
    [self.view addSubview:self.HUD];
    [self.view bringSubviewToFront:self.HUD];
    self.HUD.labelText = islocal?kInfoLocalLoad:kInfoReadingLoad;
    [self.HUD show:YES];
}

-(void)hideHud{
    [self.HUD hide:YES];
    [self.HUD removeFromSuperview];
}

#pragma mark - 点击手势
-(void)addTapGesture{
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer  alloc] initWithTarget:self action:@selector(tapOnContentView:)];
    tapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

//点击屏幕中间事件处理
- (void)tapAction
{
    if([self.toolbar isShowSubview]){
        [self.toolbar hideSubview];
    }
    if ([self.topbar isShowSubView]) {
        [self.topbar hideSubView];
    }
    
    self.isShowMenu = !self.isShowMenu;
    
    //Scroll翻页方式时动画会移位，所以去掉
    [UIView animateWithDuration:[ReaderGlobalModel shareModel].readerConfig.PageTransitionStyle == UIPageViewControllerTransitionStyleScroll?0.0:0.3
                     animations:^{
                         [self setNeedsStatusBarAppearanceUpdate];
                     }];
    
    if (self.isShowMenu) {
        
        [_toolbar show];
        [_topbar show];
        [_autoScrollReadingToolBar showOnView:self.view];
        [_phoneticReadingToolBar showOnView:self.view];
        [_phoneticReadingPlayBtn showOnView:self.view];
        
        [self.dsController onStopInteroperate];
        [self updateToolBarProgress];
    } else {
        [_toolbar hide];
        [_topbar hide];
        [_autoScrollReadingToolBar hide];
        [_phoneticReadingToolBar hide];
        [_phoneticReadingPlayBtn hide];
    }
    [_pageScrollView menuShow:self.isShowMenu];
}

//不响应上下菜单栏的点击事件
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    //屏蔽_pageController自带的点击事件
    if([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]&&gestureRecognizer.view==_pageController.view){
        return NO;
    }
    
    if (self.isShowMenu) {
        if ([self isSubView:touch.view inParentView:[ReaderToolBar class]]||[self isSubView:touch.view inParentView:[ReaderTopBar class]]) {
            return NO;
        }
    }
    return YES;
}

//判断是否为子视图
-(BOOL)isSubView:(UIView *)sub inParentView:(Class)parentClass{
    
    if ([sub isKindOfClass:parentClass]) {
        return YES;
    }
    
    if (sub.superview) {
        return [self isSubView:sub.superview inParentView:parentClass];
    }
    
    return  NO;
}

//是否启用交互手势启用
-(void)enableInteractivePopGestureRecognizer:(BOOL)enable{
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = enable;
    }
}

- (void)tapOnContentView:(UITapGestureRecognizer *)tapGestureRecognizer
{
    CGPoint point = [tapGestureRecognizer locationInView:self.view];
    if(self.isShowMenu||(point.x>MTScreenW/4&&point.x<MTScreenW*3/4&&point.y>MTScreenH/4&&point.y<MTScreenH*3/4)){//菜单栏显示时点击整屏关闭；点击屏幕中部显示菜单栏
        [self tapAction];
    } else if (![PhoneticReadingManager shareManager].isPlaying) {//语音阅读期间禁止点击翻页
        
        if([ReaderGlobalModel shareModel].readerConfig.PageTransitionStyle==UIPageViewControllerTransitionStyleScroll){//连环
            
            BOOL isHeadOrLeft = point.x<MTScreenW/4||point.y<MTScreenH/4;//左侧或顶部
            BOOL isTailOrRight = (point.x>MTScreenW*3/4&&point.y>30)||point.y>MTScreenH*3/4;//右侧或下方
            
            if(isHeadOrLeft){//点击前部、上下翻动点击头部时，显示前一页;
                [self goBeforeOrBehindViewControllerIsBefore:kLeftPagedown?NO:YES completion:nil];
            }else if(isTailOrRight){//点击后部或下部,显示后一页
                [self goBeforeOrBehindViewControllerIsBefore:NO completion:nil];
            }
            
        } else if ([ReaderGlobalModel shareModel].readerConfig.PageTransitionStyle==UIPageViewControllerTransitionStylePageCurl){//仿真、无动画
            
            BOOL isTop = point.x>MTScreenW/3&&point.x<MTScreenW*2/3&&point.y<MTScreenH/4;
            BOOL isLeft = point.x<MTScreenW/4;
            
            //非左下侧翻页时只需要加顶部的点击，左侧点击自带的；左侧下翻页时会屏蔽控件自带点击
            if((isTop||isLeft)&&!kLeftPagedown) {//只有在非左侧下翻页时，点击有前翻页
                [self tapOnViewWithPageCurlForward:NO completion:nil];
            } else {//后翻页
                [self tapOnViewWithPageCurlForward:YES completion:nil];
            }
        }
    }
}

/**连环翻页动画移到前或后一个页面*/
-(void)goBeforeOrBehindViewControllerIsBefore:(BOOL)isbefore completion:(Completion)complete{
    
    UIViewController *afterVc = isbefore?[_pageController.dataSource pageViewController:_pageController viewControllerBeforeViewController:[self currentViewController]]:[_pageController.dataSource pageViewController:_pageController viewControllerAfterViewController:[self currentViewController]];
    
    UIPageViewControllerNavigationDirection direct = isbefore?UIPageViewControllerNavigationDirectionReverse:UIPageViewControllerNavigationDirectionForward;
    [self setController:(DataViewController*)afterVc direction:direct animated:YES isDoubleSide:NO completion:^(BOOL finished) {
        if(complete)complete();
    }];
}

- (void)tapOnViewWithPageCurlForward:(BOOL)isforward completion:(Completion)complete{
    
    NSInteger currentIndex = [self currentIndex]+(isforward?1:-1);
    NSInteger count = self.dsController.pageDatas.count;
    if (currentIndex>=count||currentIndex==5||currentIndex==count-5) {
        MTLog(@"=need updateDatasource isShowhud:%d",currentIndex>=count);
        [self updateDatasource:[self currentViewController] isShowHud:currentIndex>=count isforward:isforward];
    }
    
    if(currentIndex<count){
        UIPageViewControllerNavigationDirection direct = isforward?UIPageViewControllerNavigationDirectionForward:UIPageViewControllerNavigationDirectionReverse;
        BOOL animated = ![ReaderGlobalModel shareModel].readerConfig.IsPageTransitionNoAnimate;
        [self pageControllerSetIndex:currentIndex animated:animated direct:direct isDoubleSide:animated completion:complete];
    }
}

#pragma mark - PageViewController
- (void)initPageViewController
{
    if (_pageController) {
        [self deallocPageViewController];
    }
    if (_pageScrollView) {
        [self deallocPageScrollView];
    }
    Class PageViewControllerClass = [ReaderGlobalModel shareModel].readerConfig.PageTransitionStyle==UIPageViewControllerTransitionStyleScroll?[MTPageViewController class]:[UIPageViewController class];
    _pageController = [[PageViewControllerClass alloc]initWithTransitionStyle:[ReaderGlobalModel shareModel].readerConfig.PageTransitionStyle navigationOrientation:[ReaderGlobalModel shareModel].readerConfig.PageNavigationOrientation options:nil];
    _pageController.delegate = self.dsController;
    _pageController.dataSource = self.dsController;
    _pageController.doubleSided = [ReaderGlobalModel shareModel].readerConfig.PageTurnStyle == PageTurnStyle_Simulat;
    _pageController.view.frame = CGRectMake(0, 0, MTScreenW, MTScreenH);
    
    //设置背景颜色，防止快速翻动时出现能看到白色背景的情况
    _pageController.view.backgroundColor = [ReaderGlobalModel shareModel].readerConfig.ViewBgColor;
    [self addChildViewController:_pageController];
    [self.view addSubview:_pageController.view];
    
    [self.view bringSubviewToFront:_toolbar];
    [self.view bringSubviewToFront:_topbar];
    
    for(UIGestureRecognizer *gr in _pageController.view.gestureRecognizers){
        if ([gr isKindOfClass:[UITapGestureRecognizer class]]) {
            gr.delegate = self;
        }
    }
    
    //滑动翻页时需要根据offset判断当前位置
    if([ReaderGlobalModel shareModel].readerConfig.PageTransitionStyle == UIPageViewControllerTransitionStyleScroll){
        for (UIView *v in _pageController.view.subviews) {
            if ([v isKindOfClass:[UIScrollView class]]) {
                UIScrollView *scroll = (UIScrollView *)v;
                scroll.delegate = self;
                scroll.delaysContentTouches = NO;
            }
        }
    }
}

- (void)deallocPageViewController {
    
    [_pageController willMoveToParentViewController:nil];
    [_pageController.view removeFromSuperview];
    [_pageController removeFromParentViewController];
    _pageController.delegate = nil;
    _pageController.dataSource = nil;
    _pageController = nil;
}

#pragma mark - PageScrollVerticalView
- (PageScrollVerticalView *)pageScrollView {
    
    if (!_pageScrollView) {
        _pageScrollView = [[PageScrollVerticalView alloc] init];
    }
    return _pageScrollView;
}

//上下翻页
- (void)initPageScrollView {
    
    if (_pageController) {
        [self deallocPageViewController];
    }
    
    [self.view addSubview:self.pageScrollView];
    self.pageScrollView.delegate = self;
    [self.pageScrollView menuShow:self.isShowMenu];
    
    [self.view bringSubviewToFront:_topbar];
    [self.view bringSubviewToFront:_toolbar];
}

- (void)deallocPageScrollView {
    
    [self.pageScrollView removeFromSuperview];
    self.pageScrollView.delegate = nil;
    self.pageScrollView = nil;
}

//保存一下阅读位置 now立即保存
-(void)bookmarkSaveImmediately:(BOOL)now{
    
    //小于最小间隔时间且非需要立即记录，则不保存
    if (!now && [[NSDate date] timeIntervalSince1970]-lastRecordNodeTime<MINTIMERINTERVAL)return;
    //不在书架中的书不记录
    if (![self isInBookcase:_readerBookModel.readerBook.book.bookid])return;
    
    Bookmark *cmark = [self currentBookmark];
    if(now||!([cmark.chapterid integerValue]==[lastReadnode.chapterid integerValue]&&[cmark.percent isEqualToString:lastReadnode.percent])){
        if(![[FmdbAccess shareModel] recordBooknode:cmark])//若不成功则需要重置防止进入后台时还不保存
            lastReadnode = nil;
        else
            lastReadnode = [cmark copy];
        
        self.readerBookModel.readerBook.book.rposition = [self currentReadPosition];
        [[FmdbAccess shareModel] updateBook:self.readerBookModel.readerBook.book forceUpdate:YES];
        lastRecordNodeTime = [[NSDate date] timeIntervalSince1970];
    }
}

#pragma mark - 夜间模式定时器
-(void)nightModeTimerTask{
    
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    self.nightModeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    uint64_t interval = (uint64_t)(30 * NSEC_PER_SEC);
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW,interval);
    dispatch_source_set_timer(self.nightModeTimer, start, interval, 0);
    
    __weak ReaderViewController *weakSelf = self;
    dispatch_source_set_event_handler(weakSelf.nightModeTimer, ^{
        
        __strong __typeof(self) strongSelf = weakSelf;
        if ([SettimeModel isAutoNight]) {//启用了自动夜间模式时间段
            BOOL currentIsNotNightShouldOn = [SettimeModel isInNightTimeInteval]&&![ReaderGlobalModel shareModel].readerConfig.IsNight;//非夜间模式且处在夜间模式有效时段中
            BOOL currentIsNightShouldOff = ![SettimeModel isInNightTimeInteval]&&[ReaderGlobalModel shareModel].readerConfig.IsNight;//当前是夜间模式，且不处在时间段内
            if(currentIsNotNightShouldOn||currentIsNightShouldOff){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [strongSelf.toolbar performSelectNightMode];
                    [ToastView showMsg:currentIsNotNightShouldOn?@"定时切换到夜间模式开启":@"退出定时切换到夜间模式" inView:strongSelf.view isCenter:YES];
                });
            }
        }
    });
    dispatch_resume(self.nightModeTimer);
}

-(void)addBookNode:(void(^)(void))complete{
    
    __weak ReaderViewController *weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0,0), ^{
        
        __strong __typeof(self) strongSelf = weakSelf;
        [[FmdbAccess shareModel] recordBooknode:[strongSelf currentBookmark]];
        
        _readerBookModel.readerBook.book.rposition = [strongSelf currentReadPosition];
        if([strongSelf isInBookcase:strongSelf.readerBookModel.readerBook.book.bookid]&&[[FmdbAccess shareModel] updateBook:strongSelf.readerBookModel.readerBook.book forceUpdate:YES]){
            dispatch_async(dispatch_get_main_queue(), ^{//在书架里
                [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateLocalshelNotification object:strongSelf.readerBookModel.readerBook.book];
                complete();
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                complete();
            });
        }
    });
}

#pragma mark - 自动阅读 autoScrollReadingToolBar

- (AutoScrollReadingToolBar *)autoScrollReadingToolBar {
    
    if (!_autoScrollReadingToolBar) {
        _autoScrollReadingToolBar = [[AutoScrollReadingToolBar alloc] init];
        _autoScrollReadingToolBar.delegate = self;
    }
    _autoScrollReadingToolBar.isNight = [ReaderGlobalModel shareModel].readerConfig.IsNight;
    return _autoScrollReadingToolBar;
}

- (void)deallocAutoScrollReadingToolBar {
    
    if (self.autoScrollReadingToolBar) {
        [self.autoScrollReadingToolBar removeFromSuperview];
        self.autoScrollReadingToolBar.delegate = nil;
        self.autoScrollReadingToolBar = nil;
    }
}

#pragma mark AutoScrollReadingToolBarDelegate

//速度
- (void)autoScrollReadingToolBar:(AutoScrollReadingToolBar *)toolBar currentSpeed:(NSInteger)speed {
    
    [self autoScrollReading];
}

//停止
- (void)autoScrollReadingToolBar:(AutoScrollReadingToolBar *)toolBar stopBtnClick:(UIButton *)btn {
    
    [self stopAutoScrollReading];
}

- (void)stopAutoScrollReading {
    
    [_autoScrollReadingTimer invalidate];
    _autoScrollReadingTimer = nil;
    
    [self deallocAutoScrollReadingToolBar];
    [self setupReaderBar];
    [self tapAction];
    [self.phoneticReadingPlayBtn hide];
    [_pageScrollView stopAutoScrollReadForce:YES];
}

- (void)autoScrollReading {
    
    [_autoScrollReadingTimer invalidate];
    _autoScrollReadingTimer = nil;
    
     [[UIApplication sharedApplication] setIdleTimerDisabled:YES];//自动阅读时保持屏幕常亮
    if ([ReaderGlobalModel shareModel].readerConfig.PageTurnStyle==PageTurnStyle_Updown) {//上下
        
        [_pageScrollView autoScrollRead];
    } else{//仿真、连环、无动画
        
        float interval = 30-2.5*[ReaderGlobalModel shareModel].readerConfig.autoReadingSpeed;
        _autoScrollReadingTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(autoScrollReadingAction:) userInfo:nil repeats:YES];
    }
}

//定时器任务
- (void)autoScrollReadingAction:(NSTimer *)timer {
    
    PageTurnStyle style = [ReaderGlobalModel shareModel].readerConfig.PageTurnStyle;
    [self autoScrollReadingPageStyle:style completion:^{}];
}

//根据翻页类型做自动翻页
- (void)autoScrollReadingPageStyle:(PageTurnStyle)style completion:(Completion)complete{
    
    if (style==PageTurnStyle_Simulat||style==PageTurnStyle_NoAni) {
        [self tapOnViewWithPageCurlForward:YES completion:complete];
    } else if (style==PageTurnStyle_Interlink) {
        [self goBeforeOrBehindViewControllerIsBefore:NO completion:complete];
    }
    [self bookmarkSaveImmediately:NO];
}

#pragma mark - phoneticCoverView

- (UIView *)phoneticCoverView {
    
    if (!_phoneticCoverView) {
        _phoneticCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH)];
        _phoneticCoverView.backgroundColor = [UIColor clearColor];
    }
    return _phoneticCoverView;
}

#pragma mark - ReadingPlayBtn

- (PhoneticReadingPlayBtn *)phoneticReadingPlayBtn {
    
    if (!_phoneticReadingPlayBtn) {
        //距离右侧、下侧的距离：20    宽高均是50
        float barHeight = _toolbar?_toolbar.height:_phoneticReadingToolBar.height;
        _phoneticReadingPlayBtn = [[PhoneticReadingPlayBtn alloc] initWithFrame:CGRectMake(MTScreenW-70, MTScreenH-barHeight-50-20, 50, 50)];
        _phoneticReadingPlayBtn.layer.cornerRadius = 25;
        _phoneticReadingPlayBtn.delegate = self;
    }
    return _phoneticReadingPlayBtn;
}

- (void)deallocPhoneticReadingPlayBtn {
    
    if (self.phoneticReadingPlayBtn) {
        [self.phoneticReadingPlayBtn removeFromSuperview];
        self.phoneticReadingPlayBtn.delegate = nil;
        self.phoneticReadingPlayBtn = nil;
    }
}

#pragma mark 语音 PhoneticReadingPlayBtnDelegate

- (void)phoneticReadingPlayBtnClick:(PhoneticReadingPlayBtn *)playBtn{
    
    self.phoneticCoverView.hidden = [PhoneticReadingManager shareManager].isPlaying;
    if ([PhoneticReadingManager shareManager].isPlaying) {
        
        [self deallocPhoneticReadingBar];
        [self deallocReaderBar];
        [[PhoneticReadingManager shareManager] stopPhoneticReading];
        [self setupReaderBar];
        [_topbar show];
        [_toolbar show];
        [PhoneticReadingManager shareManager].isPlaying = NO;
        [self.phoneticReadingPlayBtn showOnView:self.view];
        [self tapAction];
        [_interstitialAdView cancel];
        [_interstitialAdView dismiss];
    } else {
        
        if([ReaderGlobalModel shareModel].readerConfig.PageTurnStyle==PageTurnStyle_Updown){//上下翻页时切换到无动画进行自动语音
            Chapter *chapter = [self currentChapter];
            float percent = [self currentPercent];
            [self initPageViewController];
            [ReaderGlobalModel shareModel].readerConfig.PageTurnStyle = PageTurnStyle_NoAni;
            [self reloadCurrentPageChapter:chapter forceUpdate:NO percent:percent completion:^{
                [self resetViewAndBeginPhoneticRead];
            }];
            return;
        }
        
        [self resetViewAndBeginPhoneticRead];
        [self beginRemoteControl];
        
        //显示插屏广告
        _interstitialAdView = [[InterstitialAdView alloc] init];
        [_interstitialAdView showAdInController:self size:CGSizeMake(kAdWidth, kAdHeight) closeTime:20.0 location:InterAdInSpeek];
    }
}

-(void)resetViewAndBeginPhoneticRead{
    [self.view addSubview:self.phoneticCoverView];
    [self deallocReaderToolBar];
    [self.phoneticReadingToolBar showOnView:self.view];
    [self deallocPhoneticReadingPlayBtn];
    [self beginPhoneticReadCurrentIsInit:YES];
    [PhoneticReadingManager shareManager].isPlaying = YES;
    [self.phoneticReadingPlayBtn showOnView:self.view];
}

//语音阅读当前页
- (void)beginPhoneticReadCurrentIsInit:(BOOL)isinit {
    
    [self beginPhoneticRead:[self currentPageTextIsInit:isinit]];
}

-(void)beginPhoneticRead:(NSString *)text{
    
    if(!text)return;
    text = [text stringByReplacingOccurrencesOfString:@"\0" withString:VOICEDIVID];
    [self.view insertSubview:self.phoneticCoverView belowSubview:self.topbar];
    [self.view bringSubviewToFront:_phoneticReadingToolBar];
    [self.view bringSubviewToFront:_phoneticReadingPlayBtn];
    
    PhoneticReadingManager *manager = [PhoneticReadingManager shareManager];
    manager.delegate = self;
    manager.rate = self.phoneticReadingToolBar.speed;
    [manager startPhoneticReadingText:text];
}

/*当前页中的文字
 *begin 从头开始还是从第一句开始
 */
-(NSString *)currentPageTextIsInit:(BOOL)isinit{
    
    DataViewController *dataVc = [self currentViewController];
    NSString *ctext = dataVc.dataObject;
    NSString *ntext = [self nextPageText];
    NSString *first = [self firstTalkOfString:ctext];
    NSString *last = [self firstTalkOfString:ntext];
    if(!isinit)ctext = [ctext substringFromIndex:first.length];
    ctext = [ctext stringByAppendingString:last];//拼接被截断的最后一句话
    
    if(!ctext)
        ctext = @"";
    
    return ctext;
}

-(NSString *)firstTalkOfString:(NSString *)text{
    
    if (!text||text.length==0||[text hasPrefix:@"\0"])return @"";
    NSArray *charArray = @[@"。",@"，",@"：",@"！",@"？",@"；",@".",@",",@":",@"!",@"?",@";"];
    NSInteger index = 0;
    for (int i=0; i<text.length-1; i++) {
        NSString *c = [text substringWithRange:NSMakeRange(i, 1)];
        if([charArray containsObject:c]){
            index = i;
            break;
        }
    }
    return [text substringToIndex:index+1];
}

//下一页中的文字
-(NSString *)nextPageText{
    
    NSString *ctext = @"";
    NSInteger index = [self currentIndex]+1;
    if (index < self.dsController.pageDatas.count) {
        DataViewController *dataVc = [self.dsController viewControllerAtIndex:index];
        ctext = dataVc.dataObject;
        if(!ctext)
            ctext = @"";
    }
    
    return ctext;
}

//处理线路改变的问题
- (void)handleRouteChange:(NSNotification *)notification {
    
    NSDictionary *info = notification.userInfo;
    
    AVAudioSessionRouteChangeReason reason =
    [info[AVAudioSessionRouteChangeReasonKey] unsignedIntValue];
    
    if (reason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        
        AVAudioSessionRouteDescription *previousRoute =
        info[AVAudioSessionRouteChangePreviousRouteKey];
        
        AVAudioSessionPortDescription *previousOutput = previousRoute.outputs[0];
        NSString *portType = previousOutput.portType;
        
        if ([portType isEqualToString:AVAudioSessionPortHeadphones]) {
            //有耳机时&&正在播放：暂停播放－>继续播放
            if ([PhoneticReadingManager shareManager].isPlaying) {
                [PhoneticReadingManager shareManager].isPlaying = NO;
                [self phoneticReadingPlayBtnClick:_phoneticReadingPlayBtn];
            }
        }
    }
}

//处理中断的问题
-(void)handleInterruption:(NSNotification *)notification
{
    NSDictionary *info = notification.userInfo;
    
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if(type == AVAudioSessionInterruptionTypeBegan){
        //开始打断，停止阅读
        [self stopPhoneticReading];
    }else{
        //结束打断， 手动点击阅读
    }
}

//开始远程控制; 结束远程控制在程序进入后台&&没有播放状态
- (void)beginRemoteControl {
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    [self becomeFirstResponder];
    [self setLockScreenNowPlayingInfo];
}

//系统方法
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    
    if (event.type==UIEventTypeRemoteControl) {
        //开始 || 暂停
        if ((event.subtype==UIEventSubtypeRemoteControlPlay)||(event.subtype==UIEventSubtypeRemoteControlPause)) {
            [self phoneticReadingPlayBtnClick:nil];
        }
    }
    
    [self setLockScreenNowPlayingInfo];
    
}

//设置锁屏界面
- (void)setLockScreenNowPlayingInfo {
    
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        //标题
        NSString *title;
        DataViewController *dvc = [self currentViewController];
        if(!dvc||!dvc.chapter)title = @"";
        else title = dvc.chapter.chaptername;
       
        [dict setObject:title forKey:MPMediaItemPropertyTitle];
        [dict setObject:_readerBookModel.readerBook.book.bookname forKey:MPMediaItemPropertyArtist];
        
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    }
}

#pragma mark PhoneticReadingManagerDelegate

- (void)phoneticreadingManager:(PhoneticReadingManager *)readingManager didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
    
    //翻页
    [self autoScrollReadingPageStyle:[ReaderGlobalModel shareModel].readerConfig.PageTurnStyle completion:^{
        [self beginPhoneticReadCurrentIsInit:NO];
    }];
}

#pragma mark PhoneticReadingToolBar

- (PhoneticReadingToolBar *)phoneticReadingToolBar {
    
    if (!_phoneticReadingToolBar) {
        _phoneticReadingToolBar = [[PhoneticReadingToolBar alloc] init];
        _phoneticReadingToolBar.delegate = self;
    }
    _phoneticReadingToolBar.isNight = [ReaderGlobalModel shareModel].readerConfig.IsNight;
    return _phoneticReadingToolBar;
}

- (void)deallocPhoneticReadingBar {
    
    if (self.phoneticReadingToolBar) {
        [self.phoneticReadingToolBar removeFromSuperview];
        self.phoneticReadingToolBar.delegate = nil;
        self.phoneticReadingToolBar = nil;
    }
    if (self.topbar) {
        [self.topbar removeFromSuperview];
        self.topbar.delegate = nil;
        self.topbar = nil;
    }
}

- (void)deallocReaderToolBar {
    
    if (self.toolbar) {
        [self.toolbar removeFromSuperview];
        self.toolbar.delegate = nil;
        self.toolbar = nil;
    }
}

#pragma mark PhoneticReadingToolBarDelegate

- (void)phoneticReadingToolBar:(PhoneticReadingToolBar *)toolBar readSpeedAccelerated:(BOOL)isAccelerate {
    
    [[PhoneticReadingManager shareManager] stopPhoneticReading];
    
    [self beginPhoneticReadCurrentIsInit:YES];
}

#pragma mark 停止语音阅读，只有在当前正在播放，需要停止播放，才调用
- (void)stopPhoneticReading {
    
    if ([PhoneticReadingManager shareManager].isPlaying) {
        [self phoneticReadingPlayBtnClick:_phoneticReadingPlayBtn];
    }
}

#pragma mark - 顶部状态栏
-(UIStatusBarAnimation)preferredStatusBarUpdateAnimation{
    
    return UIStatusBarAnimationSlide;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return (isShowBookmarkMenuview||![ReaderGlobalModel shareModel].readerConfig.IsNight)?UIStatusBarStyleDefault:UIStatusBarStyleLightContent;
}

- (BOOL)prefersStatusBarHidden
{
    return !self.isShowMenu||_autoScrollReadingToolBar;
}

#pragma mark - 菜单条
- (void)setupReaderBar
{
    [self.toolbar addToView:self.view];
    [self.topbar addToView:self.view];
}

-(ReaderToolBar *)toolbar{
    
    if (!_toolbar) {
        _toolbar = [[ReaderToolBar alloc] initWithDataController:_readerBookModel];
    }
    _toolbar.delegate = self;
    _toolbar.isNight = [ReaderGlobalModel shareModel].readerConfig.IsNight;
    
    return _toolbar;
}

-(ReaderTopBar *)topbar{
    
    if (!_topbar) {
        _topbar = [[ReaderTopBar alloc] initWithDataController:_readerBookModel];
    }
    _topbar.delegate = self;
    _topbar.isNight = [ReaderGlobalModel shareModel].readerConfig.IsNight;
    
    return _topbar;
}

- (void)deallocReaderBar {
    
    if (_topbar) {
        [_topbar removeFromSuperview];
        _topbar.delegate = nil;
        _topbar = nil;
    }
    
    if (_toolbar) {
        [_toolbar removeFromSuperview];
        _toolbar.delegate = nil;
        _toolbar = nil;
    }
    [self deallocPhoneticReadingPlayBtn];
    self.isShowMenu = NO;
}

-(void)updateToolBarProgress{
    
    [self.toolbar setTotoalPages:_readerBookModel.readerBook.chapterList.count];
    
    Chapter *chapter = [self currentChapter];
    [_readerBookModel.readerBook setChapterId:chapter.chapterid];
    [self.toolbar setCurrentPage:_readerBookModel.readerBook.currentChapterIndex];
}

#pragma mark - 数据加载
//重新加载当前视图
-(void)reloadCurrentPageChapter:(Chapter*)currentChapter forceUpdate:(BOOL)force percent:(float)percent{
    
    [self reloadCurrentPageChapter:currentChapter forceUpdate:force percent:percent completion:nil];
}

-(void)reloadCurrentPageChapter:(Chapter*)currentChapter forceUpdate:(BOOL)force percent:(float)percent completion:(Completion)complete{
    
    BOOL islocal = [_readerBookModel isCurrentBookExistLocalChapter:currentChapter.chapterid];
    [self showHud:(force||islocal)];
    if ([ReaderGlobalModel shareModel].readerConfig.PageTurnStyle == PageTurnStyle_Updown) {
        
        NSString *oldChapterid = _readerBookModel.readerBook.chapterId;
        [_readerBookModel.readerBook setChapterId:currentChapter.chapterid];
        [_readerBookModel getChapterContentType:CURRENTCHAPTERCONTENT forceUpdate:force complete:^(ChapterContent *chaptercontent, TurnResult result) {
            [self hideHud];
            if(result==TurnNoNet){
                [_readerBookModel.readerBook setChapterId:oldChapterid];
                [ToastView showMsg:kContentErrorNoNetInfo inView:self.view isCenter:YES];
            }else{
                _readerBookModel.readerBook.booknodePercent=percent;
                [self loadPageScrollViewData:0 percent:percent];
            }
            if(complete)complete();
        }];
    }else{
        [_readerBookModel pageDataCenterChapter:currentChapter forceUpdate:force currentPageOrPercent:percent isPercent:YES complete:^(NSDictionary *dict) {
            [self.dsController updateDatasource:dict];
            [self pageControllerSetIndex:self.dsController.index animated:NO direct:UIPageViewControllerNavigationDirectionForward isDoubleSide:NO completion:^{
                if(complete)complete();
            }];
            [self hideHud];
        }];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
        for (UIView *sub in self.view.subviews) {
            if([sub isKindOfClass:[MBProgressHUD class]]){
                [sub removeFromSuperview];
                [ToastView showMsg:@"请求超时，请检查网络设置" inView:self.view isCenter:YES];
            }
        }
    });
}

- (void)loadPageviewDatasource:(NSDictionary *)dict{
    
    [self.dsController updateDatasource:dict];
    
    if ([ReaderGlobalModel shareModel].readerConfig.PageTurnStyle == PageTurnStyle_Updown) {
        [self reloadCurrentPageChapter:_readerBookModel.readerBook.chapter forceUpdate:NO percent:_readerBookModel.readerBook.booknodePercent];
    }
}

- (void)loadPageScrollViewData:(int)direct percent:(float)percent{
    
    [self.pageScrollView loadPageCurrent:_readerBookModel.readerBook.currentChaptercontent pre:_readerBookModel.readerBook.preChaptercontent next:_readerBookModel.readerBook.nextChaptercontent curentPercent:percent direct:direct];
    [self getPreAndNextData];
}

//获取前后章节
-(void)getPreAndNextData{
    
    [_readerBookModel getChapterContentType:PRECHAPTERCONTENT forceUpdate:NO complete:^(ChapterContent *chaptercontent, TurnResult result) {
        if(result == TurnNoMore){
            _readerBookModel.readerBook.preChaptercontent = nil;
        }
    }];
    
    [_readerBookModel getChapterContentType:NEXTCHAPTERCONTENT forceUpdate:NO complete:^(ChapterContent *chaptercontent, TurnResult result) {
        if(result == TurnNoMore){
            _readerBookModel.readerBook.nextChaptercontent = nil;
        }
    }];
}

//失败重新加载的通知
-(void)refreshConten:(NSNotification *)noti{
    [self reloadCurrentPageChapter:noti.object forceUpdate:YES percent:0];
}

- (void)updateFont {
    
    if (self.globalModel.readerConfig.PageTurnStyle == PageTurnStyle_Updown) {
        [self.pageScrollView loadPageCurrent:_readerBookModel.readerBook.currentChaptercontent pre:_readerBookModel.readerBook.preChaptercontent next:_readerBookModel.readerBook.nextChaptercontent curentPercent:[lastReadnode.percent floatValue] direct:0];
    } else {
        //字体行间距等变更时需要重新计算分页并定位
        [self reloadCurrentPageChapter:[self currentChapter] forceUpdate:NO percent:[self currentPercent]];
    }
}

- (void)pageControllerSetIndex:(NSInteger)index animated:(BOOL)animated direct:(UIPageViewControllerNavigationDirection)direct isDoubleSide:(BOOL)isDouble completion:(Completion)complete
{
    DataViewController *dataVc = [self.dsController viewControllerAtIndex:index];
    
    [self setController:dataVc direction:direct animated:animated isDoubleSide:isDouble completion:^(BOOL finished) {
        if(complete)complete();
    }];
}

#pragma mark - 设置当前controller
-(void)setController:(DataViewController *)controller direction:(UIPageViewControllerNavigationDirection)direction animated:(BOOL)animated isDoubleSide:(BOOL)isDouble completion:(void (^)(BOOL finished))completion{
    
    if(!controller||self.dsController.pageIsAnimating)return;
    
    if(isDouble){
        BackViewController *backViewController = [BackViewController new];
        [self.pageController setViewControllers:@[controller,backViewController] direction:direction animated:animated completion:^(BOOL finished) {
            if(completion)completion(finished);
        }];
    }else{
        [self.pageController setViewControllers:@[controller] direction:direction animated:animated completion:^(BOOL finished) {
            if(completion)completion(finished);
        }];
    }
}

#pragma mark - DatasourceViewControllerDelegate 翻页时的位置判断
-(void)datasourceViewController:(DatasourceViewController *)datasourceViewController isForward:(BOOL)isforward shouldGetData:(BOOL)needget currentViewcontroller:(DataViewController *)vc
{
    willVc = vc;
    [self bookmarkSaveImmediately:NO];
    [self.HUD hide:YES];
    if(self.isShowMenu)
        [self tapAction];//菜单栏显示时，虽不能点击切换，但是可以滑动切换，滑动时自动关闭菜单栏
    
    DataViewController *currentVc = [self currentViewController];
    BOOL isFirst = currentVc.currentPage==0&&_readerBookModel.readerBook.isFirstOrLastChapter;//第一章第一页
    BOOL isLast = currentVc.totalPage==currentVc.currentPage+1&&_readerBookModel.readerBook.isFirstOrLastChapter;//最后一章最后一页
    BOOL isHeadTurn = (!vc&&!(isLast||isFirst));//到数组的首尾时的滚动
    
    //三种情形需要更新数据：翻到了需要重新获取数据的位置；无网络重试一次；没有获取到内容且不是首尾页；
    if(needget||[vc.dataObject isEqualToString:kContentErrorNoNetInfo]||isHeadTurn){
        NSInteger ci = [self.dsController indexOfViewController:[self currentViewController]];
        BOOL needshow = ci==0||ci==self.dsController.pageDatas.count-1;
        [self updateDatasource:currentVc isShowHud:needshow isforward:isforward];
    }
    
    BOOL isInterlink = [ReaderGlobalModel shareModel].readerConfig.PageTurnStyle==PageTurnStyle_Interlink;
    if (isforward) {//前翻
        
        if (!vc&&isLast){//翻页不成功、翻到顶了
            [ToastView showMsg:AREADY_TO_LAST inView:self.view isCenter:YES];
        }else if(vc&&[ReaderGlobalModel shareModel].readerConfig.IsPageTransitionNoAnimate){//无动画直接跳下一页
            
            [self setController:vc direction:UIPageViewControllerNavigationDirectionForward animated:NO isDoubleSide:NO completion:^(BOOL finished) {}];
        }
        
    }else{//后退
        
        if (!vc&&isFirst){//翻页不成功、翻到顶了
            if(!isInterlink||(isInterlink&&[self isScrollHead]))
                [ToastView showMsg:AREADY_TO_FRONT inView:self.view isCenter:YES];
        }else if(vc&&[ReaderGlobalModel shareModel].readerConfig.IsPageTransitionNoAnimate){//无动画章节内部，直接跳下一页
            
            [self setController:vc direction:UIPageViewControllerNavigationDirectionForward animated:NO isDoubleSide:NO completion:^(BOOL finished) {}];
        }
    }
}

- (BOOL)isScrollHead{
    
    BOOL isEnd = NO;
    for (UIView *v in _pageController.view.subviews) {
        if ([v isKindOfClass:[UIScrollView class]]) {
            UIScrollView *scroll = (UIScrollView *)v;
            MTLog(@"scroll.contentOffset:%@",NSStringFromCGPoint(scroll.contentOffset));
            //滑动翻页时需要根据offset判断当前位置是否是第一页
            return scroll.contentOffset.x==0;
        }
    }
    return isEnd;
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    BOOL isForwardScr = scrollView.contentOffset.y==0&&scrollView.contentOffset.x > MTScreenW;
    BOOL isBackScr = scrollView.contentOffset.y==0&&scrollView.contentOffset.x < MTScreenW;
    
    if ((isForwardScr||isBackScr) && !willVc) {//向后或向前滑
        MTLog(@"滑动到最%@一页了，更新数据源",isForwardScr?@"后":@"前");
        [self updateDatasource:[self currentViewController] isShowHud:YES isforward:isForwardScr];
    }
}

//show 提示加载还是以静默的方式加载 show=YES说明已经是在最后一页了
-(void)updateDatasource:(DataViewController *)vc isShowHud:(BOOL)show isforward:(BOOL)isforward{
    
    if(show){//20181216 增加最后一章最后一页判断
        BOOL isLast = vc.totalPage==vc.currentPage+1&&_readerBookModel.readerBook.isFirstOrLastChapter;//最后一章最后一页
        if(isLast){
            [ToastView showMsg:AREADY_TO_LAST inView:self.view isCenter:YES];
            return;
        }else{
            [self showHud:NO];
        }
    }
    
    if(isExcutingUpdate)return;
    isExcutingUpdate = YES;
    [self.readerBookModel pageDataCenterChapter:vc.chapter forceUpdate:NO currentPageOrPercent:vc.currentPage isPercent:NO complete:^(NSDictionary *dict) {
        
        [self.dsController updateDatasource:dict];
        MTLog(@"=!!!updateDatasource");
        if (show){
            if([ReaderGlobalModel shareModel].readerConfig.PageTransitionStyle==UIPageViewControllerTransitionStyleScroll){
                [self goBeforeOrBehindViewControllerIsBefore:!isforward completion:nil];
            }else if([ReaderGlobalModel shareModel].readerConfig.PageTransitionStyle==UIPageViewControllerTransitionStylePageCurl){
                [self tapOnViewWithPageCurlForward:isforward completion:nil];
            }
        }
        [self hideHud];
        isExcutingUpdate = NO;
    }];
}

#pragma mark - 当前对象
//当前阅读的章节
-(Chapter *)currentChapter{
    
    Chapter *chapter = [self currentViewController].chapter;
    if (!chapter) {//上下翻页
        chapter = _readerBookModel.readerBook.chapter;
    }
    return chapter;
}

//当前页记成书签的对象
-(Bookmark *)currentBookmark{
    
    if ([ReaderGlobalModel shareModel].readerConfig.PageTurnStyle == PageTurnStyle_Updown) {
        return _pageScrollView.bookmark;
    }
    
    DataViewController *currentVc = [self currentViewController];
    if(!currentVc)return nil;
    NSString *bookid = _readerBookModel.readerBook.book.bookid;
    NSString *chapterid = currentVc.chapter.chapterid;
    NSString *chaptername = currentVc.chapter.chaptername;
    
    if(!bookid||!chapterid||!chaptername)
        return nil;
    
    NSString *percent=[NSString stringWithFormat:@"%.2f",[self currentPercent]];
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:bookid,chapterid,percent?percent:@"",chaptername,nil] forKeys:[NSArray arrayWithObjects:@"bookid",@"chapterid",@"percent",@"chaptername",nil]];
    Bookmark *currentBookmark = [[Bookmark alloc] initWithDictionary:dict];
    
    return currentBookmark;
}

-(NSInteger)currentIndex{
    
    NSArray *array = _pageController.viewControllers;
    if(array&&array.firstObject){
        UIViewController *firstVc = array.firstObject;
        if([firstVc isKindOfClass:[DataViewController class]])
            return [self.dsController indexOfViewController:(DataViewController*)firstVc];
    }
    return 0;
}

-(DataViewController *)currentViewController{
    if(!_pageController)return nil;
    NSArray *array = _pageController.viewControllers;
    if(array&&array.firstObject){
        UIViewController *firstVc = array.firstObject;
        if([firstVc isKindOfClass:[DataViewController class]]){
            return (DataViewController *)firstVc;
        }
    }
    return nil;
}

-(float)currentPercent{
    
    float p;
    DataViewController *currentVc = [self currentViewController];
    if(currentVc){
        //获取阅读章内百分比
        float totoal = currentVc.totalPage;
        p = totoal>0 ? currentVc.currentPage/totoal:0;
    }else{
        p = [self.pageScrollView.bookmark.percent floatValue];
    }
    
    return p;
}

//当前章节位置
- (NSString *)currentReadPosition {
    
    return [NSString stringWithFormat:@"%d",(int)_readerBookModel.readerBook.currentChapterIndex+1];
}

#pragma mark - 上下翻页
#pragma mark PageScrollVerticalViewDelegate
-(void)pageScrollVerticalView:(PageScrollVerticalView *)view shouldSkipChapterIspre:(BOOL)isPre{
    
    isPre?[self gotoPreChapterIslast:YES]:[self gotoNextChapter];
}

-(void)pageScrollVerticalView:(PageScrollVerticalView *)view changeToChapter:(NSString *)chapterid{
    
    self.readerBookModel.readerBook.chapterId = chapterid;
    [self.readerBookModel getChapterContentType:CURRENTCHAPTERCONTENT forceUpdate:NO complete:^(ChapterContent *chaptercontent, TurnResult result) {
        [self.readerBookModel getChapterContentType:PRECHAPTERCONTENT forceUpdate:NO complete:^(ChapterContent *chaptercontent, TurnResult result) {}];
        [self.readerBookModel getChapterContentType:NEXTCHAPTERCONTENT forceUpdate:NO complete:^(ChapterContent *chaptercontent, TurnResult result) {}];
    }];
}

-(void)pageScrollVerticalView:(PageScrollVerticalView *)view scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self bookmarkSaveImmediately:NO];
}

#pragma mark 切换数据
-(void)gotoNextChapter{
    
    NSString *nextContent = _readerBookModel.readerBook.nextChaptercontent.chaptercontent;
    if (nextContent&&![[DownloadManager shareInstance] isErrorContent:nextContent]) {//已经获取到了下一章的内容
        [self loadNextContent];
    }else{
        //没有获取到下一章内容
        if(!_readerBookModel.readerBook.isFirstOrLastChapter){
            [self showHud:NO];
        }
        __weak ReaderViewController *weakSelf = self;
        [_readerBookModel getChapterContentType:NEXTCHAPTERCONTENT forceUpdate:NO complete:^(ChapterContent *chaptercontent, TurnResult result) {
            __strong __typeof(self) strongSelf = weakSelf;
            [strongSelf hideHud];
            switch (result) {
                case TurnSuc:
                    [strongSelf loadNextContent];
                    break;
                case TurnNoNet:
                    [ToastView showMsg:kContentErrorNoNetInfo inView:strongSelf.view isCenter:YES];
                    [strongSelf stopPhoneticReading];
                    [strongSelf stopAutoScrollReading];
                    break;
                case TurnNoMore:
                    [ToastView showMsg:AREADY_TO_LAST inView:strongSelf.view isCenter:YES];
                    [strongSelf stopPhoneticReading];
                    [strongSelf stopAutoScrollReading];
                    break;
                default:
                    break;
            }
        }];
    }
}

-(void)gotoPreChapterIslast:(BOOL)isGoLast{
    
    NSString *preContent = _readerBookModel.readerBook.preChaptercontent.chaptercontent;
    if (preContent&&![[DownloadManager shareInstance] isErrorContent:preContent]){//已经获取到了上一章的内容
        
        [self loadPreContent:isGoLast];
    }else{
        //没有获取到上一章内容
        if(!_readerBookModel.readerBook.isFirstOrLastChapter){
            [self showHud:NO];
        }
        [_readerBookModel getChapterContentType:PRECHAPTERCONTENT forceUpdate:NO complete:^(ChapterContent *chaptercontent, TurnResult result) {
            [self hideHud];
            switch (result) {
                case TurnSuc:
                    [self loadPreContent:isGoLast];
                    break;
                case TurnNoNet:
                    [ToastView showMsg:kContentErrorNoNetInfo inView:self.view isCenter:YES];
                    break;
                case TurnNoMore:
                    [ToastView showMsg:AREADY_TO_FRONT inView:self.view isCenter:YES];
                    break;
                    
                default:
                    break;
            }
        }];
    }
}

//切换显示下一章的内容
-(void)loadNextContent{
    
    _readerBookModel.readerBook.preChaptercontent = _readerBookModel.readerBook.currentChaptercontent;
    _readerBookModel.readerBook.currentChaptercontent = _readerBookModel.readerBook.nextChaptercontent;
    _readerBookModel.readerBook.nextChaptercontent = [[ChapterContent alloc] init];
    _readerBookModel.readerBook.preChapter = _readerBookModel.readerBook.chapter;
    _readerBookModel.readerBook.chapter = _readerBookModel.readerBook.nextChapter;
    _readerBookModel.readerBook.nextChapter = [Chapter new];
    MTLog(@"当前章已切换为:%@",_readerBookModel.readerBook.currentChaptercontent.chaptername);
    
    if(_readerBookModel.readerBook.currentChaptercontent.chaptercontent)
        [self loadPageScrollViewData:1 percent:0];
}

/** 切换显示上一章的内容
 * isGoLast=YES前一章的最后一页,NO第一页
 * skiped=YES,只切换数据不做跳转
 */
-(void)loadPreContent:(BOOL)isGoLast{
    
    _readerBookModel.readerBook.nextChaptercontent = _readerBookModel.readerBook.currentChaptercontent;
    _readerBookModel.readerBook.currentChaptercontent = _readerBookModel.readerBook.preChaptercontent;
    _readerBookModel.readerBook.preChaptercontent = [[ChapterContent alloc] init];
    _readerBookModel.readerBook.nextChapter = _readerBookModel.readerBook.chapter;
    _readerBookModel.readerBook.chapter = _readerBookModel.readerBook.preChapter;
    _readerBookModel.readerBook.preChapter = [Chapter new];
    MTLog(@"当前章已切换为:%@",_readerBookModel.readerBook.currentChaptercontent.chaptername);
    
    if(_readerBookModel.readerBook.currentChaptercontent.chaptercontent)
        [self loadPageScrollViewData:-1 percent:1];
}

#pragma mark - 加入书架
-(void)addToBookshelf:(void(^)(void))complete{
    
    NSString *bookid = _readerBookModel.readerBook.book.bookid;
    BOOL isInBookcase = [self isInBookcase:bookid];//在书架中
    
    if (!isInBookcase) {//提示用户加入书架
        
        NSString *msg;
        msg=@"喜欢就放入书架吧~";
        
        MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@"添加书籍" message:msg preferredStyle:UIAlertControllerStyleAlert];
        MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"添加" style:UIAlertActionStyleDefault handler:^(MISAlertAction * _Nonnull action) {
            [BookcaseOprationController addBookcase:bookid success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateBookshelfNotification object:bookid];
            } failed:^(int stateCode, NSString *failMsg) {
                [ToastView showMsg:@"加入书架失败，请手动添加" inView:self.view isCenter:YES];
            }];
            if(complete)complete();
        }];
        MISAlertAction *cancelAction = [MISAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(MISAlertAction * _Nonnull action) {
            [FileManager removeLocalBook:bookid];//未添加书架的书，需清理本地缓存
            if(complete)complete();
        }];
        [alertController addAction:okAction];
        [alertController addAction:cancelAction];
        [alertController showInViewController:self animated:YES];
        
    }else{
        if(complete)complete();
    }
}

//判断书籍是否在书架中
-(BOOL)isInBookcase:(NSString *)bookid{
    
    BOOL hasExitst = NO;
    for (Book *book in [ReaderGlobalModel shareModel].bookshelf) {
        if ([book.bookid integerValue]==[bookid integerValue]) {
            hasExitst = YES;
            break;
        }
    }
    return hasExitst;
}

//（对于有下载的书自动）加入书架
-(void)autoAddBookcase:(NSString *)bookid{
    if(![self isInBookcase:bookid]){
        [BookcaseOprationController addBookcase:bookid success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateBookshelfNotification object:bookid];
            MTLog(@"点击下载，添加书架成功");
        } failed:^(int stateCode, NSString *failMsg) {
            MTLog(@"点击下载，添加书架失败");
        }];
    }
}

#pragma mark - ReaderToolBarDelegate 底部菜单栏
-(void)readerToolBar:(ReaderToolBar *)bar fontsizeSet:(NSInteger)fontsize{
    
    [ReaderGlobalModel shareModel].readerConfig.FontSize = fontsize;
    [self updateFont];
}

-(void)readerToolBar:(ReaderToolBar *)bar linespace:(CGFloat)space{
    
    [ReaderGlobalModel shareModel].readerConfig.LineSpace = space;
    [self updateFont];
}

-(void)readerToolBar:(ReaderToolBar *)bar backgroudColor:(ReadBackgroud)bgcolor{
    
    _pageController.view.backgroundColor = [ReaderGlobalModel shareModel].readerConfig.ViewBgColor;
    [ReaderGlobalModel shareModel].readerConfig.BgColorType = bgcolor;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kChangePageColorNotification object:@(bgcolor)];
    
    if (self.globalModel.readerConfig.PageTurnStyle != PageTurnStyle_Updown) {
        NSInteger currentIndex = [self currentIndex];
        [self pageControllerSetIndex:currentIndex animated:NO direct:UIPageViewControllerNavigationDirectionForward isDoubleSide:NO completion:nil];
    }
}

//字体设置、更多设置
- (void)readerToolBar:(ReaderToolBar *)bar setBtnClick:(NSInteger)btnTag{
    
    if (btnTag == 1) {
        FontSetViewController *fontSetVC = [[FontSetViewController alloc] init];
        MTNavigationController *nav = [[MTNavigationController alloc] initWithRootViewController:fontSetVC];
        [self presentViewController:nav animated:YES completion:^{}];
    } else {
        SettingViewController *setVC = [[SettingViewController alloc] init];
        MTNavigationController *nav = [[MTNavigationController alloc] initWithRootViewController:setVC];
        [self presentViewController:nav animated:YES completion:^{}];
    }
}

-(void)readerToolBar:(ReaderToolBar *)bar setIsNight:(BOOL)isnight{
    
    @synchronized (self) {
        [ReaderGlobalModel shareModel].readerConfig.IsNight = isnight;
        [[NSNotificationCenter defaultCenter] postNotificationName:kChangePageColorNotification object:@(isnight)];//当前页夜间模式的切换得单独通知
        //播放按钮图标切换
        [self.phoneticReadingPlayBtn showOnView:self.view];
        self.toolbar.isNight = isnight;
        self.topbar.isNight = isnight;
        
        if ([ReaderGlobalModel shareModel].readerConfig.PageTurnStyle == PageTurnStyle_Updown) {
            _pageScrollView.backgroundColor = [ReaderGlobalModel shareModel].readerConfig.ViewBgColor;
        } else {
            _pageController.view.backgroundColor = [ReaderGlobalModel shareModel].readerConfig.ViewBgColor;
        }
        [self setNeedsStatusBarAppearanceUpdate];//日间和夜间模式的状态栏不一样
    };
}

-(void)readerToolBar:(ReaderToolBar *)bar changePageStyle:(PageTurnStyle)style{
    
    //切换之前先获取当前章节和阅读百分比
    Chapter *chapter = [self currentChapter];
    float percent = [self currentPercent];
    
    PageTurnStyle lastStyle = [ReaderGlobalModel shareModel].readerConfig.PageTurnStyle;
    [ReaderGlobalModel shareModel].readerConfig.PageTurnStyle = style;
    
    if(lastStyle!=style){//只有当选择的翻页方式跟上次不同时才做处理
        if (style == PageTurnStyle_Updown) {//从其他切换到上下
            [self initPageScrollView];
            [self reloadCurrentPageChapter:chapter forceUpdate:NO percent:percent];
        }else if(lastStyle == PageTurnStyle_Updown){//从上下切换到其他
            [self initPageViewController];
            [self reloadCurrentPageChapter:chapter forceUpdate:NO percent:percent];
        } else{//仿真、连环、无动画间切换
            NSInteger currentIndex = [self currentIndex];
            [self initPageViewController];
            [self pageControllerSetIndex:currentIndex animated:NO direct:UIPageViewControllerNavigationDirectionForward isDoubleSide:NO completion:nil];
        }
    }
}

//自动阅读 代理
- (void)readerToolBar:(ReaderToolBar *)bar autoReadingBtnClick:(UIButton *)btn {
    
    [self deallocReaderBar];
    [self.autoScrollReadingToolBar showOnView:self.view];
    //模拟点击，隐藏状态栏
    [self tapAction];
    
    [self autoScrollReading];
}

//横屏、竖屏 代理
-(void)readerToolBar:(ReaderToolBar *)bar orientationIsLandscape:(BOOL)isLandscape {
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    MTLog(@"当前屏幕方向：%d，是否设置为横屏：%d",(int)orientation,isLandscape);
    if([MTRotatingScreen isOrientationLandscape] == isLandscape){//重复点击当前设置不响应
        MTLog(@"重复点击当前屏幕方向，无响应");
        return;
    }else{
        [ReaderGlobalModel shareModel].readerConfig.orientationIsLandscape = isLandscape;
    }
    
    [self readerViewSetorientationIsLandscape:isLandscape];
}

//旋转屏幕方向
- (void)readerViewSetorientationIsLandscape:(BOOL)isLandscape {
    
    self.view.backgroundColor = [ReaderGlobalModel shareModel].readerConfig.ViewBgColor;
    
    if (!isIpad) {//iphone
        _isScreenRotating = YES;
        
        [MTRotatingScreen forceOrientation:isLandscape?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait];
        [self deallocReaderBar];
        //重新显示topBar、toolBar
        [self setupReaderBar];
        [self tapAction];
        
        //重置pageView
        [self resetPageView];
        
        _isScreenRotating = NO;
    } else {//ipad
        
        [self deallocReaderBar];
        
        [ReaderGlobalModel shareModel].readerConfig.ipadIsSupportLandscape=YES;
        [MTRotatingScreen forceOrientation:isLandscape?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait];
    }
}

//系统方法， 旋转结束调用
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    
    if (isIpad) {    //只有iPad调用
        //重新显示topBar、toolBar
        [self setupReaderBar];
        [self tapAction];
        [ReaderGlobalModel shareModel].readerConfig.ipadIsSupportLandscape=NO;
        //重置pageView
        [self resetPageView];
    }
}

- (void)resetPageView {
    
    Chapter *chapter = [self currentChapter];
    float percent = [self currentPercent];
    PageTurnStyle style = [ReaderGlobalModel shareModel].readerConfig.PageTurnStyle;
    if (style == PageTurnStyle_Updown) {
        [self deallocPageScrollView];
        [self initPageScrollView];
    } else {
        _dsController = nil;
        [self deallocPageViewController];
        [self initPageViewController];
    }
    [self reloadCurrentPageChapter:chapter forceUpdate:NO percent:percent];
    [self.phoneticReadingPlayBtn showOnView:self.view];
}

- (BOOL)shouldAutorotate {
    
    return !_isScreenRotating;
}

-(void)readerToolBar:(ReaderToolBar *)bar selectedChapter:(Chapter *)chapter{
    
    [self reloadCurrentPageChapter:chapter forceUpdate:NO percent:0];
}

-(void)readerToolBar:(ReaderToolBar *)bar isShowBookmarkMenuView:(BOOL)show{
    
    isShowBookmarkMenuview = show;
    [self setNeedsStatusBarAppearanceUpdate];
    if( self.isShowMenu)[self tapAction];
}

#pragma mark  下载
- (void)readerToolBar:(ReaderToolBar *)bar downloadType:(DownloadType)downloadType {
    
    Book *book = _readerBookModel.readerBook.book;
    
    //TODO判断章节列表的完整性
    NSArray *chapterList = _readerBookModel.readerBook.chapterList;
    //获取当前章节
    Chapter *currentChapter = [chapterList firstObject];//默认当前章节为第一章，全本缓存时从第一章开始
    if(downloadType!=Download_all)
        currentChapter = [self currentChapter];
    
    DownloadModel *download = [[DownloadModel alloc] init];
    download.book = book;
    download.chapter = currentChapter;
    download.chapterList = chapterList;
    download.downloadType = downloadType;
    
    //下载操作
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        __strong DownloadModel *sdownload = download;
        __strong Book *sbook = book;
        [self downloadOperationDownloadModel:sdownload book:sbook];
    });
}

-(void)downloadOperationDownloadModel:(DownloadModel *)model book:(Book *)book {
    
    if(!book.bookid)return;
    [self autoAddBookcase:book.bookid];
    
    if(![[DownloadManager shareInstance] addDownload:model]){
        __weak ReaderViewController *weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.toolbar showWaitDownload];});
    }
}

-(void)readerToolBar:(ReaderToolBar *)bar downloadCancel:(BOOL)cancel {
    
    [bar cancelDownload];
    [[NSNotificationCenter defaultCenter] postNotificationName:kDownloadTaskCancelShouldDeleteQueueNotification object:_readerBookModel.readerBook.book];
}

//预加载五章
-(void)preDownloadData{
    
    NSArray *list = _readerBookModel.readerBook.chapterList;
    [[[DownloadManager alloc] init] downloadBook:_readerBookModel.readerBook.book currentChapter:[self currentChapter] chapterList:list downloadType:Download_5 needNoti:NO];
}

//用户取消下载的通知处理：直接点击取消按钮或者非wifi提示框选择取消下载
- (void)downloadTaskCancel:(NSNotification *)noti {
    
    Book *book = noti.object;
    if ([book.bookid integerValue]==[_readerBookModel.readerBook.book.bookid integerValue]) {
        [self.toolbar cancelDownload];
    }
}

- (void)downloadTaskFinishOne:(NSNotification *)noti {
    
    if(![_toolbar isDownloadViewShow])//只有在下载视图显示时，才更新界面，避免正在下载时频繁更新界面造成点击菜单卡顿
        return;
    NSDictionary *dic = noti.object;
    if([dic[@"hasCancel"] boolValue])
        return;//用户取消任务时，子线程中正在执行的下载任务结束发来的通知不处理
    
    BOOL isWait = [[dic objectForKey:@"isWait"] boolValue];
    if (isWait) {
        [self.toolbar showWaitDownload];
        return;
    }
    
    float percent = [dic[@"percent"] floatValue];
    
    //下载的章节是否已经存在
    BOOL exist = [dic[@"exist"] boolValue];
    
    /**
     *  通知中包含bookId，标示某一本正在下载的书，正在下载，再次进入，还处于下载状态，否则，重置按钮状态
     */
    NSString *bookid = dic[@"bookId"];
    
    Book *book = _readerBookModel.readerBook.book;
    if ([bookid integerValue] == [book.bookid integerValue]) {
        
        if (exist) {
            [ToastView showMsg:@"下载的章节本地已存在" inView:self.view isCenter:YES];
        } else {
            if (percent >= 1) {
                [ToastView showMsg:@"下载已完成" inView:self.view isCenter:YES];
            }
        }
        //进度条进度
        [self.toolbar setProgressPercent:percent exist:exist];
    }
}

#pragma mark - ReaderTopBarDelegate 顶部菜单栏

-(void)readerTopBar:(ReaderTopBar *)topBar backBtnClick:(id)sender{
    
    if (isIpad)[self readerViewSetorientationIsLandscape:NO];
    //停止语音播放
    [self stopPhoneticReading];
    __weak typeof(self) weakSelf = self;
    [self addToBookshelf:^{
        __strong __typeof(self) strongSelf = weakSelf;
        __weak typeof(self) weakSelf2 = strongSelf;
        [strongSelf addBookNode:^{
            __strong __typeof(self) strongSelf2 = weakSelf2;
            
            if([MTRotatingScreen isOrientationLandscape]){
                if (!isIpad)[weakSelf readerViewSetorientationIsLandscape:NO];
                [[NSNotificationCenter defaultCenter] postNotificationName:kFreshLocalshelNotification object:nil];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{//ipad需要在主线程执行
                [strongSelf2 releasSource];
                [strongSelf2.navigationController popViewControllerAnimated:YES];
            });
        }];
    }];
    // 进入时禁用了滑动返回手势，返回时应启用
    [self enableInteractivePopGestureRecognizer:YES];
}

-(void)readerTopBar:(ReaderTopBar *)topBar selectContent:(NSInteger)content{
    
    [EbookNetRequest submitError:_readerBookModel.readerBook.currentChaptercontent.bookid chapterId:_readerBookModel.readerBook.currentChaptercontent.chapterid type:content success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        [ToastView showMsg:[NSString stringWithFormat:@"%@",[dict objectForKey:@"message"]] inView:self.view isCenter:YES];
    } failed:^(int stateCode, NSString *failMsg) {
        [ToastView showMsg:failMsg inView:self.view isCenter:YES];
    }];
}

//刷新章节
-(void)readerTopBar:(ReaderTopBar *)topBar refreshChapterBtnclick:(UIButton *)btn{
    
    [self reloadCurrentPageChapter:[self currentChapter] forceUpdate:YES percent:0];
}

//转到书城
-(void)readerTopBar:(ReaderTopBar *)topBar redirectStoreBtnclick:(UIButton *)btn{
    
    WebViewController *webVC = [[WebViewController alloc] init];
    id data = [[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData];
    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSString *url = dic[@"data"][@"bookinfo"];
    
    if([url hasPrefix:@"http"]&&[url containsString:@"%d"]){
        url = [NSString stringWithFormat:url,[_readerBookModel.readerBook.book.bookid intValue]];
        url = [url stringByAppendingFormat:@"&token=%@",[[NSUserDefaults standardUserDefaults]objectForKey:kToken]];
        webVC.url = url;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

- (void)readerTopBar:(ReaderTopBar *)topBar changeSourceBtnClick:(id)sender {
    
    SelectSourceViewController *selSourceVC = [[SelectSourceViewController alloc] init];
    selSourceVC.bookid = _readerBookModel.readerBook.book.bookid;
    MTNavigationController *nav = [[MTNavigationController alloc] initWithRootViewController:selSourceVC];
    [self presentViewController:nav animated:YES completion:^{}];
}

- (void)readerTopBar:(ReaderTopBar *)topBar sourceBtnClick:(id)sender {
    
    MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@""
                                                                               message:@"是否跳转到原网页阅读？"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
    MISAlertAction *cancelAction = [MISAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    
    MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(MISAlertAction *action) {
        NSString *urlStr = _readerBookModel.readerBook.chapter.sourceurl;
        if (urlStr.length>0&&![urlStr hasPrefix:@"http"]) {
            urlStr = [NSString stringWithFormat:@"http://%@", urlStr];
        }
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [alertController showInViewController:self animated:YES];
}

-(void)readerTopBar:(ReaderTopBar *)topBar clickedTranscodingButtonAtIndex:(NSInteger)buttonIndex{
    
    switch (buttonIndex) {
        case 0:{//服务声明
            WebViewController *webVC = [[WebViewController alloc] init];
            id data = [[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData];
            NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            webVC.webViewTitle = @"服务声明";
            webVC.url = dic[@"data"][@"mianze"];
            [self.navigationController pushViewController:webVC animated:YES];
        }
            break;
        case 1://查看源网页
        {
            [self readerTopBar:_topbar sourceBtnClick:nil];
        }
            break;
        default:
            break;
    }
}

-(void)cancelTimer{
    // 取消定时器
    if(self.nightModeTimer){
        dispatch_cancel(self.nightModeTimer);
        self.nightModeTimer = nil;
    }
    [_autoScrollReadingTimer invalidate];
    _autoScrollReadingTimer = nil;
}

-(void)releasSource{
    
    [self cancelTimer];
    [ReaderGlobalModel shareModel].attributes = nil;
    
    [self deallocPageViewController];
    [self deallocPageScrollView];
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    [self.toolbar didReceiveMemoryWarningOperator];
    MTLog(@"didReceiveMemoryWarning ReaderViewController");
}

@end
